package asimes.leetcode;

/**
 * Created by Asimes on 2016/9/19.
 */
public class AddTwoNumbers {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
//        l1.next = new ListNode(4);
//        l1.next.next = new ListNode(3);
        ListNode l2 = new ListNode(9);
        l2.next = new ListNode(9);
//        l2.next.next = new ListNode(4);
        ListNode result = addTwoNumbers(l1, l2);
        while (result != null) {
            System.out.println(result.val);
            result = result.next;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null;
        ListNode cur = null;
        ListNode tmp;
        int result;
        int digit = 0;
        int tail = 0;
        int m, n;
        while (true) {
            if (l1 == null && l2 == null && digit == 0)
                break;
            if (l1 == null) m = 0;
            else {
                m = l1.val;
            }
            if (l2 == null) n = 0;
            else {
                n = l2.val;
            }

            result = m + n;
            tail = result % 10;
            if(tail+digit>=10){
               tmp = new ListNode((tail + digit)%10);
                digit = (tail + digit) / 10;

            }else{
                tmp = new ListNode(tail + digit);
                digit = result / 10;
            }

            if (head == null) {
                head = tmp;
                cur = head;
            } else {
                cur.next = tmp;
                cur = cur.next;
            }

            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        return head;
    }

}
